const list = document.querySelector('.list')
const loading = document.querySelector('.loading')

function createItem(content, id) {
  let itemHtml = document.createElement('div')
  itemHtml.className = 'item'
  let a = document.createElement('a')
  a.href = `todo.html?id=${id}&form=index`
  a.innerHTML = content

  let close = document.createElement('span')
  close.innerHTML = '&times;'
  close.className = 'close'
  close.setAttribute('data-id', id)
  itemHtml.append(a)
  itemHtml.append(close)
  return itemHtml
}

$.ajax({
  url: 'https://api.yizhanketang.cn/api/v1/todos',
  success: function (res) {
    loading.style.display = 'none'
    if (res.data.length > 0) {
      res.data.forEach(function (item) {
        list.append(createItem(item.content, item.objectId))
      })

    } else {
      list.innerHTML = `<div class="empty">暂无数据</div>`
    }
  },
  error: function () {
    alert('网络错误')
  }
})

const formBtn = document.querySelector('.form button')
formBtn.addEventListener('click', function () {
  const content = document.querySelector('.form [name=content]')
  const desc = document.querySelector('.form [name=description]')

  if (!content.value) {
    alert('标题不能为空')
  } else {
    loading.style.display = 'flex'
    $.ajax({
      method: 'POST',
      url: 'https://api.yizhanketang.cn/api/v1/todos',
      data: {
        content: content.value,
        description: desc.value
      },
      success: function (res) {
        list.prepend(createItem(res.data.content, res.data.objectId))
        content.value = ''
        desc.value = ''
        loading.style.display = 'none'
      },
      error: function () {
        alert('网络错误')
        loading.style.display = 'none'
      }
    })
  }
})

// 事件委托
list.addEventListener('click', function (event) {
  // if(event.target.nodeName === 'SPAN') {
  if(event.target.className === 'close') {
    const _this = event.target
    if (confirm('确定要删除此项数据吗？')) {
      loading.style.display = 'flex'
      $.ajax({
        type: 'POST',
        url: `https://api.yizhanketang.cn/api/v1/todos/${_this.getAttribute('data-id')}/delete`,
        success(res) {
          // alert('删除失败')
          _this.parentElement.remove()
          loading.style.display = 'none'
        },
        error() {
          alert('删除失败')
          loading.style.display = 'none'
        }
      })
    }
  }
})





